package leetcode.sword;

public class Solution53_1 {

    public static void main(String[] args) {
        int[] ss = new int[]{5,7,7,8,8,10};
        System.out.println(search(ss,8));
//        System.out.println(2 + ((5-2)>>1));
    }

    public static int search(int[] nums, int target) {
        //先二分查找target位置
        int left = 0, right = nums.length-1, mid = 0;
        while(left<=right){
            mid = left + ((right-left)>>1); //这里+的优先级高于>>，故加括号
            if(nums[mid]==target) break;
            if(nums[mid]>target){
                right = mid-1;
            }else{
                left = mid+1;
            }
        }
        if(left>right) return 0; //没找到
        //找到了，但可能不是第一个,需要向前向后找
        int first = mid, last = mid;
        while(first>=0&&nums[first]==target) first--;
        while(last<nums.length&&nums[last]==target) last++;
        return last - first - 1;
    }
}
